package com.ctv.my.customview.MaiCustomView.CitySelector.view;

import android.content.Context;
import android.os.Handler;
import android.os.Message;
import android.util.AttributeSet;
import android.util.Log;
import android.view.View;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.ExpandableListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.ctv.my.customview.MaiCustomView.CitySelector.bean.Root;
import com.ctv.my.customview.MaiCustomView.CitySelector.util.CharacterParser;
import com.ctv.my.customview.MaiCustomView.CitySelector.util.PinyinComparator;
import com.ctv.my.customview.MaiCustomView.CitySelector.adapter.GridViewAdapter;
import com.ctv.my.customview.MaiCustomView.CitySelector.adapter.MyExpandableListViewAdapter;
import com.ctv.my.customview.MaiCustomView.CitySelector.bean.City;
import com.ctv.my.customview.MaiCustomView.CitySelector.bean.Province;
import com.ctv.my.customview.R;
import com.google.gson.Gson;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by ms on 2017/7/11.
 */

public class CitySelectorView extends RelativeLayout {
    private final static String TAG = CitySelectorView.class.getSimpleName();
    private Context mContext;
    //当前定位城市
    private View headerLocation;
    private TextView tevLocation;
    private final int LAYOUT_HEADER_LOCATION = R.layout.city_select_header_view_location;
    private City mLocationCity;
    //当前热门城市
    private View headerHot;
    private final int LAYOUT_HEADER_HOT = R.layout.city_select_header_view_hot;
    private GridViewAdapter gridViewAdapter;
    private List<City> mHotCityList = new ArrayList<>();
    //城市列表
    private final int LAYOUT_CITY_LIST = R.layout.city_select_list_view;
    private ExpandableListView expandableListView;
    private MyExpandableListViewAdapter myExpandableListViewAdapter;
    //城市列表数据
    private List<Province> cityList = new ArrayList<>();
    private PinyinComparator pinyinComparator;
    /**
     * 汉字转换成拼音的类
     */
    private CharacterParser characterParser;

    /**
     * 在代码中直接new一个会调用
     *
     * @param context
     */
    public CitySelectorView(Context context) {
        super(context);
        this.mContext = context;
        initHeader(context);
        initCityView(context);
        initCityListData();
    }

    /**
     * 在xml布局文件中使用会调用此函数
     *
     * @param context
     * @param attrs
     */
    public CitySelectorView(Context context, AttributeSet attrs) {
        super(context, attrs);
        this.mContext = context;
        initHeader(context);
        initCityView(context);
        initCityListData();
    }

    /**
     * 在xml布局文件中调用Custom View,并且Custom View标签中还有自定义属性时,这里调用的还是第二个构造函数.
     *
     * @param context
     * @param attrs
     * @param defStyleAttr
     */
    public CitySelectorView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        this.mContext = context;
        initHeader(context);
        initCityView(context);
        initCityListData();
    }

    private void initHeader(Context context) {
        //当前定位城市
        headerLocation = View.inflate(context, LAYOUT_HEADER_LOCATION, null);
        tevLocation = (TextView) headerLocation.findViewById(R.id.tev_location);
        tevLocation.setOnClickListener(onClickListener);
        //当前热门城市
        headerHot = View.inflate(context, LAYOUT_HEADER_HOT, null);
        MyGridView gridView = (MyGridView) headerHot.findViewById(R.id.gv_hot);
        gridViewAdapter = new GridViewAdapter(context, mHotCityList, gridView);
        gridView.setAdapter(gridViewAdapter);
        gridView.setOnItemClickListener(onItemClickListener);
    }

    private void initCityView(Context context) {
        View view = View.inflate(context, LAYOUT_CITY_LIST, CitySelectorView.this);
        expandableListView = (ExpandableListView) view.findViewById(R.id.expandListView);
        expandableListView.setGroupIndicator(null);
        SideBar sidebar = (SideBar) view.findViewById(R.id.sideBar);
        TextView tevDialog = (TextView) view.findViewById(R.id.tev_dialog);
        sidebar.setTextView(tevDialog);//绑定textView
        myExpandableListViewAdapter = new MyExpandableListViewAdapter(context, cityList);
        expandableListView.setAdapter(myExpandableListViewAdapter);
        expandableListView.addHeaderView(headerLocation);
        expandableListView.addHeaderView(headerHot);
        expandableListView.setOnChildClickListener(onChildClickListener);
        //屏蔽父级点击事件，默认不点击收缩。如需收缩，设为false，或者屏蔽
        expandableListView.setOnGroupClickListener(new ExpandableListView.OnGroupClickListener() {
            @Override
            public boolean onGroupClick(ExpandableListView parent, View v, int groupPosition, long id) {
                return true;
            }
        });
        expandableListView.setOnScrollListener(new AbsListView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(AbsListView view, int scrollState) {

            }

            @Override
            public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
                Log.e(TAG, firstVisibleItem + "");

            }
        });
        //设置右侧触摸监听
        sidebar.setOnTouchingLetterChangedListener(new SideBar.OnTouchingLetterChangedListener() {

            @Override
            public void onTouchingLetterChanged(String s) {
                //该字母首次出现的位置
                if (s.equals("定位")) {
                    expandableListView.setSelection(0);
                    return;
                }
                if (s.equals("热门")) {
                    expandableListView.setSelection(1);
                    return;
                }
                int position = myExpandableListViewAdapter.getPositionForSection(s.charAt(0));
                if (position != -1) {
                    expandableListView.setSelectedGroup(position);
                }
            }
        });
    }

    private ExpandableListView.OnChildClickListener onChildClickListener = new ExpandableListView.OnChildClickListener() {
        @Override
        public boolean onChildClick(ExpandableListView parent, View v, int groupPosition, int childPosition, long id) {
            if (parent != null && cityList.size() > 0) {
                City city = cityList.get(groupPosition).getCity().get(childPosition);
                if (mSelectClickCallback == null) {
                    Log.e(TAG, "请先设置选择回调");
                    return true;
                }
                mSelectClickCallback.chooseCity(city);
            }
            return true;
        }
    };

    private AdapterView.OnItemClickListener onItemClickListener = new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            if (id != -1 && cityList.size() > 0) {
                City city = (City) gridViewAdapter.getItem(position);
                if (mSelectClickCallback == null) {
                    Log.e(TAG, "请先设置选择回调");
                    return;
                }
                mSelectClickCallback.chooseCity(city);
            }
        }
    };

    private OnClickListener onClickListener = new OnClickListener() {
        @Override
        public void onClick(View v) {
            if (mSelectClickCallback == null) {
                Log.e(TAG, "请先设置选择回调");
                return;
            }
            mSelectClickCallback.chooseCity(mLocationCity);
        }
    };

    /**
     * 设置定位和热门城市数据,主线程调用。
     *
     * @param locationCity 当前定位的城市数据
     * @param hotCityList  热门城市列表
     */
    public void setData(City locationCity, List<City> hotCityList) {
        this.mLocationCity = locationCity;
        if (hotCityList != null) {
            this.mHotCityList.addAll(hotCityList);
        }
        tevLocation.setText(locationCity.getName() + "");
        gridViewAdapter.notifyDataSetChanged();
    }

    private SelectClickCallback mSelectClickCallback;

    /**
     * 设置选择回调
     *
     * @param mSelectClickCallback
     */
    public void setSelectClickCallback(SelectClickCallback mSelectClickCallback) {
        this.mSelectClickCallback = mSelectClickCallback;
    }

    /**
     * 选择回调
     */
    public interface SelectClickCallback {
        void chooseCity(City city);
    }

    private void initCityListData() {
        //实例化汉字转拼音类
        characterParser = CharacterParser.getInstance();
        pinyinComparator = new PinyinComparator();
        new Thread(new Runnable() {

            @Override
            public void run() {
                // TODO Auto-generated method stub
                StringBuilder sb = new StringBuilder();
                InputStream inCity;//城市数据文件
                InputStream inDuoYinZi;//多音字文件
                BufferedReader bf;
                BufferedReader bf2;
                try {
                    inCity = mContext.getResources().openRawResource(
                            R.raw.province_data);
                    bf = new BufferedReader(new InputStreamReader(inCity, "UTF-8"));
                    String line;
                    while ((line = bf.readLine()) != null) {
                        sb.append(line);
                    }
                    //多音字文件
                    Map<String, String> duoYinZiMap = new HashMap<String, String>();
                    inDuoYinZi = mContext.getResources().openRawResource(
                            R.raw.duoyinzi);
                    bf2 = new BufferedReader(new InputStreamReader(inDuoYinZi, "UTF-8"));
                    String line2;
                    while ((line2 = bf2.readLine()) != null) {
                        String[] arr = line2.split("#");
                        if (arr[1] != null && !"".equals(arr[1])) {
                            String[] dyzs = arr[1].split("/");
                            for (String dyz : dyzs) {
                                if (dyz != null && !"".equals(dyz)) {
                                    //key:多音词 value:多音词首字拼音
                                    duoYinZiMap.put(dyz.trim(), arr[0]);
                                }
                            }
                        }
                    }
                    //城市数据文件
                    Root root = new Gson().fromJson(sb.toString(), Root.class);
                    List<Province> sourceDateList = new ArrayList<>();
                    int mSize = root.getProvince().size();
                    String provinceName = "";
                    for (int i = 0; i < mSize; i++) {
                        Province province = new Province();
                        provinceName = root.getProvince().get(i).getName();
                        province.setName(provinceName);
                        province.setCity(root.getProvince().get(i).getCity());
                        province.setCode(root.getProvince().get(i).getCode());
                        //汉字转换成拼音
                        String pinyin = characterParser.getSelling(provinceName, duoYinZiMap);
                        String sortString = pinyin.substring(0, 1).toUpperCase();
                        // 正则表达式，判断首字母是否是英文字母
                        if (sortString.matches("[A-Z]")) {
                            province.setSortLetters(sortString.toUpperCase());
                        } else {
                            province.setSortLetters("#");
                        }
                        sourceDateList.add(province);
                    }
                    // 根据a-z进行排序源数据
                    Collections.sort(sourceDateList, pinyinComparator);
                    Message message = handler.obtainMessage();
                    message.obj = sourceDateList;
                    message.what = GET_LIST_DATA;
                    handler.sendMessage(message);
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                } finally {

                }
            }
        }).start();
    }

    private static final int GET_LIST_DATA = 101;
    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case GET_LIST_DATA:
                    List<Province> mList = (List<Province>) msg.obj;
                    if (mList != null && mList.size() > 0) {
                        cityList.addAll(mList);
                    }
                    myExpandableListViewAdapter.notifyDataSetChanged();
                    int size = myExpandableListViewAdapter.getGroupCount();
                    for (int i = 0; i < size; i++) {
                        //默认全部展开
                        expandableListView.expandGroup(i);
                    }
                    break;
            }
        }
    };

    @Override
    protected void onDetachedFromWindow() {
        super.onDetachedFromWindow();
        Log.d(TAG, "onDetachedFromWindow");
        if (handler != null) {
            handler.removeMessages(GET_LIST_DATA);
            handler = null;
        }
    }
}
